//
//  BCSString.swift
//  BCFoundation
//
//  Created by Basic on 2019/9/3.
//  swift String 扩展


import Foundation

public extension String {
    
    //MARK: - 编码、解码
    /// 将原始的url编码为合法的url
    func bc_encoded() -> String {
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
            .urlQueryAllowed)
        return encodeUrlString ?? ""
    }
    
    /// 将编码后的url转换回原始的url
    func bc_decoded() -> String {
        return self.removingPercentEncoding ?? ""
    }
    
    ///String 转 Dictionary<String, Any>
    func bc_toDictionary() -> Dictionary<String, Any>? {
        guard let jsonData:Data = self.data(using: .utf8) else {
            return nil
        }
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
        if dict != nil {
            return dict as? Dictionary<String, Any>
        }
        return nil
    }
    
    //MARK: - 进制转换
    ///16进制字符串转10进制数值
    func bc_toTenHexNum() -> Int {
       let str = self.uppercased()
        var sum:Int = 0
       for i in str.utf8 {
           sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
           if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
               sum -= 7
           }
       }
       return sum
    }
    
    //MARK: - 关键字查找
    /// 根据关键字前缀、后缀查找关键字位置（包含关键字，需要自己剔除）
    func bc_findKey(prefix:String, suffix:String) -> [NSRange] {
        var results:[NSRange] = []
        let regulaStr = "\(prefix)((?!(\(prefix)|\(suffix))).)*\(suffix)"
        let regex = try? NSRegularExpression(pattern: regulaStr, options: .caseInsensitive)
        let matchResults = regex?.matches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: self.count))
        for match in matchResults ?? [] {
            results.append(match.range)
        }
        return results;
    }
}
